package cn.chenxinjie.hrm.service.impl;

import cn.chenxinjie.hrm.constant.UserConstants;
import cn.chenxinjie.hrm.domain.VipUser;
import cn.chenxinjie.hrm.dto.SmsDto;
import cn.chenxinjie.hrm.mapper.VipUserMapper;
import cn.chenxinjie.hrm.service.IVerifyCodeService;
import cn.chenxinjie.hrm.util.AjaxResult;
import cn.chenxinjie.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 陈鑫杰
 * @date 2022/3/18 15:25
 */
@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VipUserMapper vipUserMapper;

    @Override
    public AjaxResult createCode(String key) throws IOException {
        // 生成一个4位数的验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 将key和code验证码存入redis中
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.SECONDS);
        // 将code基于Base64加密
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(100,40,arrayOutputStream,code);
        BASE64Encoder encoder = new BASE64Encoder();
        String baseCode = encoder.encode(arrayOutputStream.toByteArray());
        return AjaxResult.me().setResultObj(baseCode);
    }

    @Override
    public AjaxResult sendSmsCode(SmsDto dto) {
        // 参数校验以及判断手机号是否已经注册
        String mobile = dto.getMobile();
        VipUser vipUser = new VipUser();
        vipUser.setPhone(mobile);
        VipUser one = vipUserMapper.selectOne(vipUser);
        Assert.isNull(one,"手机号已经注册,请直接登录!");
        // 判断图片验证码是否正确
        Object o = redisTemplate.opsForValue().get(dto.getImageCodeKey());
        Assert.notNull(o,"图片验证码无效!");
        Assert.isTrue(dto.getImageCode().equalsIgnoreCase(o.toString()),"图片验证码错误,请重新输入");
        // 手机号和图片验证码都有效,生成短信验证码,发送短信
        String code = VerifyCodeUtils.generateVerifyCode(6, "0123456789");
        // 发送短信,用打印代替
        System.out.println("您的验证码是:"+code);
        // 保存到redis中
        redisTemplate.opsForValue().set(UserConstants.USER_REGISTER + mobile, code, 5, TimeUnit.SECONDS);
        return AjaxResult.me();
    }
}
